package com.faintlight.controller;

import com.faintlight.model.User;
import com.faintlight.service.UserService;
import me.chanjar.weixin.mp.api.WxMpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    private final UserService userService;
    private final WxMpService wxMpService;

    public UserController(UserService userService, WxMpService wxMpService) {
        this.userService = userService;
        this.wxMpService = wxMpService;
        logger.info("✅ 用户控制器初始化完成");
    }

    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getUserById(@PathVariable Long id) {
        User user = userService.getUserById(id);
        int temperature = userService.getUserTemperature(id);
        LocalDateTime lastActive = userService.getUserLastActive(id);
        Map<String, Object> vo = new HashMap<>();
        vo.put("id", user.getId());
        vo.put("name", user.getNickname());
        vo.put("avatarUrl", user.getAvatarUrl());
        vo.put("temperature", temperature);
        vo.put("lastActive", lastActive == null ? "" : lastActive.toString());
        return ResponseEntity.ok(vo);
    }

    @PostMapping("/login")
    public ResponseEntity<User> wechatLogin(@RequestParam String code) {
        logger.info("📱 微信登录请求, code={}", code);
        if (code == null || code.trim().isEmpty()) {
            logger.warn("❌ 微信登录失败: code 为空");
            throw new RuntimeException("微信登录失败: code 为空");
        }
        try {
            String openId = "test_user_001";
            String nickname = "温暖测试用户";
            String avatarUrl = "https://via.placeholder.com/64";
            User user = userService.getOrCreateUser(openId, nickname, avatarUrl);
            logger.info("✅ 用户登录成功, ID={}", user.getId());
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            logger.error("❌ 微信登录失败", e);
            throw new RuntimeException("微信登录失败", e);
        }
    }
}